// 初始化 markdown-it
const md = window.markdownit();

new Vue({
    el: '#app',
    data: {
        conversations: [],
        currentConversation: null, // 当前选中的对话
        displayedUsername: '开始', // 显示的用户名
        inputMessage: '',
        username: '',
        showLogin: false,
        showRegister: false,
        menuVisible: false,
        isLoggedIn: false,
        password: '',
        sourceDocuments: [], // 存储来源文档
        showDocumentModal: false, // 控制文档内容弹窗的显示
        currentDocument: null, // 当前选中的文档
        registerUsername: '',
        registerPassword: '',
        localUsers: [], // 存储本地用户数据
        isLoading: false, // 新增的加载状态
    },
    mounted() {
        // 从 localStorage 获取已登录的用户名
        const storedUsername = localStorage.getItem('username');
        if (storedUsername) {
            this.username = storedUsername;
            this.displayedUsername = storedUsername;
            this.isLoggedIn = true;
        }

        // 初始化时加载已保存的对话历史
        this.loadChatHistory();
        this.localUsers = JSON.parse(localStorage.getItem('localUsers')) || [];

        // 初始加载后自动滚动
        this.$nextTick(() => {
            this.scrollToBottom();
        });

        // 验证 markdown-it 是否加载正确
        if (typeof window.markdownit !== 'function' || typeof md.render !== 'function') {
            console.error('markdown-it is not a function. Ensure markdown-it.js is correctly loaded.');
        } else {
            console.log('markdown-it is loaded correctly.');
        }
    },
    updated() {
        this.$nextTick(() => {
            if (this.currentConversation && this.currentConversation.messages) {
                this.currentConversation.messages.forEach((message, index) => {
                    if (message.chart) {
                        const chartRef = this.$refs[`chart-${index}`];
                        if (chartRef && chartRef.length > 0) {
                            const chartDom = chartRef[0];
                            if (chartDom) {
                                // 如果已有 ECharts 实例，先销毁它
                                if (chartDom.__echarts_instance__) {
                                    echarts.dispose(chartDom);
                                }
                                // 初始化 ECharts 实例，并应用主题（如有）
                                const myChart = echarts.init(chartDom, 'macarons');
                                myChart.setOption(message.chart.option);
                                myChart.resize();
                            }
                        }
                    }
                });
            }
            // 调用自动滚动方法
            this.scrollToBottom();
        });
    },
    methods: {
        // 自动滚动到底部的方法
        scrollToBottom() {
            const chatMessages = this.$refs.chatMessages;
            if (chatMessages) {
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }
        },
        loadChatHistory() {
            if (this.isLoggedIn && this.username !== '开始') {
                const storedConversations = JSON.parse(localStorage.getItem(`conversations_${this.username}`)) || [];
                this.conversations = storedConversations;
                if (this.conversations.length > 0) {
                    this.currentConversation = this.conversations[0];
                    // 如果当前对话没有消息，添加初始消息
                    if (this.currentConversation.messages.length === 0) {
                        this.addInitialMessage();
                    }
                } else {
                    // 如果没有对话，自动创建一个默认对话
                    this.addNewConversation('默认对话');
                }
            } else {
                if (this.conversations.length > 0) {
                    this.currentConversation = this.conversations[0];
                    // 如果当前对话没有消息，添加初始消息
                    if (this.currentConversation.messages.length === 0) {
                        this.addInitialMessage();
                    }
                } else {
                    // 如果没有对话，自动创建一个默认对话
                    this.addNewConversation('默认对话');
                }
            }
        },
        saveChatHistory() {
            if (this.isLoggedIn && this.username !== '开始') {
                localStorage.setItem(`conversations_${this.username}`, JSON.stringify(this.conversations));
            }
        },
        addNewConversation(name) {
            const newConv = {
                id: Date.now() + Math.random(), // 添加唯一 ID
                name: name || `对话${this.conversations.length + 1}`,
                messages: []
            };
            this.conversations.push(newConv);
            this.currentConversation = newConv;
            // 添加初始消息
            this.addInitialMessage();
            this.saveChatHistory();
        },
        addInitialMessage() {
            const initialMessage = {
                text: "你好，我是心语智能对话数据报表助手，请问有什么可以帮助您的吗？",
                user: false,
                isTable: false,
                chart: null,
                sourceDocument: null
            };
            this.currentConversation.messages.push(initialMessage);
            this.saveChatHistory();
        },
        deleteConversation(index) {
            if (this.conversations.length === 1) {
                // 使用 SweetAlert2 显示警告消息
                Swal.fire({
                    title: '提示',
                    text: '必须至少保留一个对话',
                    icon: 'warning'
                });
            } else {
                // 使用 SweetAlert2 显示确认对话框
                Swal.fire({
                    title: '确认删除',
                    text: `确定要删除对话 "${this.conversations[index].name}" 吗？`,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    reverseButtons: true,
                })
                    .then((result) => {
                        if (result.isConfirmed) {
                            // 如果要删除的是当前对话，切换到另一个对话
                            const isCurrent = this.currentConversation === this.conversations[index];
                            this.conversations.splice(index, 1);
                            this.saveChatHistory();

                            if (isCurrent) {
                                if (this.conversations.length > 0) {
                                    this.currentConversation = this.conversations[0];
                                    // 如果新的当前对话没有消息，添加初始消息
                                    if (this.currentConversation.messages.length === 0) {
                                        this.addInitialMessage();
                                    }
                                } else {
                                    this.currentConversation = null;
                                }
                            }

                            // 使用 SweetAlert2 显示删除成功的消息
                            Swal.fire({
                                title: '已删除!',
                                text: '对话已被删除。',
                                icon: 'success'
                            });
                        }
                    });
            }
        },
        addConversationPrompt() {
            Swal.fire({
                title: '请输入新对话的名称',
                input: 'text',
                inputValue: `对话${this.conversations.length + 1}`,
                showCancelButton: true,
                confirmButtonText: '创建',
                cancelButtonText: '取消',
                inputValidator: (value) => {
                    if (!value) {
                        return '对话名称不能为空!';
                    }
                    if (this.conversations.some(conv => conv.name === value)) {
                        return '该对话名称已存在，请选择其他名称。';
                    }
                    return null;
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    this.addNewConversation(result.value);
                    Swal.fire('成功', '新对话已创建。', 'success');
                }
            });
        },
        renameConversation(index) {
            Swal.fire({
                title: '请输入新的对话名称:',
                input: 'text',
                inputValue: this.conversations[index].name,
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputValidator: (value) => {
                    if (!value) {
                        return '对话名称不能为空!';
                    }
                    if (this.conversations.some((conv, idx) => conv.name === value && idx !== index)) {
                        return '该对话名称已存在，请选择其他名称。';
                    }
                    return null;
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    this.updateConversationName(index, result.value);
                    Swal.fire('成功', '对话名称已更新。', 'success');
                }
            });
        },
        updateConversationName(index, newName) {
            if (newName && this.conversations[index]) {
                this.conversations[index].name = newName;
                this.saveChatHistory();
            }
        },
        selectConversation(conv) {
            this.currentConversation = conv;
            // 如果选中的对话没有消息，添加初始消息
            if (this.currentConversation.messages.length === 0) {
                this.addInitialMessage();
            }
        },
        openDocument(doc) {
            this.currentDocument = doc;
            this.showDocumentModal = true;
        },
        closeDocumentModal() {
            this.showDocumentModal = false;
            this.currentDocument = null;
        },
        // 发送消息
        async sendMessage() {
            if (this.inputMessage.trim() !== '') {
                // 将用户输入的消息添加到当前对话中
                this.currentConversation.messages.push({
                    text: this.inputMessage,
                    user: true,
                    isTable: false,
                    chart: null,
                    sourceDocument: null // 初始化为 null
                });
                this.saveChatHistory();
                const userMessage = this.inputMessage;
                console.log(`用户: ${userMessage}`); // 打印用户消息到控制台
                this.inputMessage = '';

                // 添加加载消息
                const loadingMessage = {
                    text: '正在思考...',
                    user: false,
                    isLoading: true, // 标记为加载中
                    isTable: false,
                    chart: null,
                    sourceDocument: null
                };
                this.currentConversation.messages.push(loadingMessage);
                this.saveChatHistory();

                // 自动滚动到底部
                this.$nextTick(() => {
                    this.scrollToBottom();
                });

                try {
                    const response = await fetch('http://localhost:8080/textAnalysis', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ message: userMessage })
                    });

                    if (!response.ok) {
                        throw new Error(`Server error: ${response.statusText}`);
                    }

                    const responseData = await response.json();

                    // 假设 responseData 包含 answer、fileName 和 fileContent
                    const { answer, fileName, fileContent } = responseData;

                    if (fileName && fileContent && answer) {
                        // 处理 answer
                        this.processAnswer(answer, userMessage);

                        // 附加 sourceDocument 到最后一条消息
                        const lastMessageIndex = this.currentConversation.messages.length - 1;
                        if (lastMessageIndex >= 0) {
                            this.$set(this.currentConversation.messages[lastMessageIndex], 'sourceDocument', {
                                name: fileName,
                                content: fileContent
                            });
                        }

                        this.saveChatHistory();
                    } else {
                        // 仅处理 answer
                        this.processAnswer(answer, userMessage);
                    }
                    // 打印机器人的回复到控制台
                    console.log(`机器人: ${answer}`);

                } catch (error) {
                    console.error('Error:', error);
                    // 替换加载消息为错误消息
                    const loadingMsgIndex = this.currentConversation.messages.findIndex(msg => msg.isLoading);
                    if (loadingMsgIndex !== -1) {
                        this.currentConversation.messages.splice(loadingMsgIndex, 1, {
                            text: `Error: ${error.message}`,
                            user: false,
                            isLoading: false,
                            isTable: false,
                            chart: null,
                            sourceDocument: null
                        });
                        this.saveChatHistory();
                    }
                }
            }
        },
        processAnswer(answer, userMessage) {
            // 找到加载消息的索引
            const loadingMsgIndex = this.currentConversation.messages.findIndex(msg => msg.isLoading);

            // 如果找到加载消息，准备替换的基础
            let replaceIndex = loadingMsgIndex !== -1 ? loadingMsgIndex : this.currentConversation.messages.length;

            // 假设 answer 是一个 JSON 字符串，需要解析
            let answerData;
            try {
                answerData = JSON.parse(answer);
            } catch (error) {
                console.log('Answer is not a JSON string, treating as plain text.');
                const newMessage = {
                    text: answer,
                    user: false,
                    isTable: false,
                    chart: null,
                    sourceDocument: null
                };
                if (loadingMsgIndex !== -1) {
                    // 替换加载消息
                    this.$set(this.currentConversation.messages, loadingMsgIndex, newMessage);
                } else {
                    // 添加新消息
                    this.currentConversation.messages.push(newMessage);
                }
                this.saveChatHistory();
                return;
            }

            // 检查是否需要绘制图表
            const shouldDrawChart = userMessage.includes('图') ||
                userMessage.includes('柱状图') ||
                userMessage.includes('饼图') ||
                userMessage.includes('折线图');

            if (shouldDrawChart && Array.isArray(answerData) && answerData.length > 0) {
                // 确定图表类型
                let chartType = 'bar'; // 默认柱状图
                if (userMessage.includes('饼图')) {
                    chartType = 'pie';
                } else if (userMessage.includes('折线图')) {
                    chartType = 'line';
                }

                // 生成图表配置
                const chartOption = this.generateChartOption(chartType, answerData);
                console.log('Generated Chart Option:', JSON.stringify(chartOption, null, 2));

                // 创建图表消息
                const chartMessage = {
                    text: '',
                    user: false,
                    isTable: false,
                    chart: { type: chartType, option: chartOption, rendered: false },
                    sourceDocument: null
                };

                if (loadingMsgIndex !== -1) {
                    // 替换加载消息
                    this.$set(this.currentConversation.messages, loadingMsgIndex, chartMessage);
                } else {
                    // 添加新消息
                    this.currentConversation.messages.push(chartMessage);
                }

                this.saveChatHistory();

            } else if (Array.isArray(answerData) && answerData.length > 0) {
                // 动态生成表格
                const tableHeaders = Object.keys(answerData[0]);
                let tableHTML = `
          <table class="table table-bordered table-striped table-hover table-sm custom-table">
            <thead class="thead-dark">
              <tr>
        `;
                tableHeaders.forEach(header => {
                    tableHTML += `<th>${header}</th>`;
                });
                tableHTML += `
              </tr>
            </thead>
            <tbody>
        `;
                answerData.forEach(row => {
                    tableHTML += `<tr>`;
                    tableHeaders.forEach(header => {
                        tableHTML += `<td>${row[header]}</td>`;
                    });
                    tableHTML += `</tr>`;
                });
                tableHTML += `
            </tbody>
          </table>
        `;

                // 创建表格消息
                const tableMessage = {
                    text: tableHTML,
                    user: false,
                    isTable: true,
                    chart: null,
                    sourceDocument: null
                };

                if (loadingMsgIndex !== -1) {
                    // 替换加载消息
                    this.$set(this.currentConversation.messages, loadingMsgIndex, tableMessage);
                } else {
                    // 添加新消息
                    this.currentConversation.messages.push(tableMessage);
                }
                this.saveChatHistory();
            } else if (typeof answerData === 'object' && answerData !== null) {
                // 将对象作为普通文本显示
                const textMessage = {
                    text: JSON.stringify(answerData, null, 2),
                    user: false,
                    isTable: false,
                    chart: null,
                    sourceDocument: null
                };
                if (loadingMsgIndex !== -1) {
                    // 替换加载消息
                    this.$set(this.currentConversation.messages, loadingMsgIndex, textMessage);
                } else {
                    // 添加新消息
                    this.currentConversation.messages.push(textMessage);
                }
                this.saveChatHistory();
            } else {
                // 无效的回答
                const noDataMessage = {
                    text: 'No data available or invalid JSON response.',
                    user: false,
                    isTable: false,
                    chart: null,
                    sourceDocument: null
                };
                if (loadingMsgIndex !== -1) {
                    // 替换加载消息
                    this.$set(this.currentConversation.messages, loadingMsgIndex, noDataMessage);
                } else {
                    // 添加新消息
                    this.currentConversation.messages.push(noDataMessage);
                }
                this.saveChatHistory();
            }
        },
        showLoginDialog() {
            this.showLogin = true;
            this.menuVisible = false; // 隐藏选择框
        },
        showRegisterDialog() {
            this.showRegister = true;
            this.menuVisible = false;
        },
        // 注册功能
        handleRegister() {
            // 检查用户名是否已存在
            if (this.localUsers.some(user => user.username === this.registerUsername)) {
                Swal.fire({
                    icon: 'error',
                    title: '错误',
                    text: '用户名已存在！'
                });
                return;
            }

            // 添加新用户到本地存储
            this.localUsers.push({
                username: this.registerUsername,
                password: this.registerPassword
            });
            localStorage.setItem('localUsers', JSON.stringify(this.localUsers));

            // 清空表单并关闭弹窗
            this.registerUsername = '';
            this.registerPassword = '';
            this.showRegister = false;

            Swal.fire('成功', '注册成功！', 'success');
        },
        logout() {
            this.isLoggedIn = false;
            this.menuVisible = false; // 隐藏选择框
            localStorage.removeItem('username');
            this.displayedUsername = '开始';
            this.currentConversation = null;
            window.location.reload();
        },
        async handleLogin(event) {
            // 首先检查本地用户
            const localUser = this.localUsers.find(user =>
                user.username === this.username && user.password === this.password
            );

            if (localUser) {
                // 本地用户验证成功
                this.loginSuccess();
                return;
            }

            try {
                // 如果本地验证失败，尝试后端验证
                const response = await fetch('http://localhost:8080/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        user_name: this.username,
                        password: this.password
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }

                const data = await response.json();

                if (data.code === 1 && data.msg === "success") {
                    this.loginSuccess();
                } else {
                    this.loginFailed();
                }
            } catch (error) {
                console.error("登录错误:", error);
                this.loginFailed();
            }
        },
        loginSuccess() {
            localStorage.setItem('username', this.username);
            this.isLoggedIn = true;
            this.showLogin = false;

            // 更新显示的用户名
            this.displayedUsername = this.username; // 只在登录成功后更新

            Swal.fire('成功', '登录成功！', 'success');
            this.loadChatHistory();
        },
        loginFailed() {
            Swal.fire({
                icon: 'error',
                title: '错误',
                text: '登录失败，请检查用户名或密码'
            });
        },
        toggleMenu(event) {
            this.menuVisible = !this.menuVisible;
            if (this.menuVisible) {
                document.addEventListener('click', this.handleClickOutside);
            } else {
                document.removeEventListener('click', this.handleClickOutside);
            }
        },
        handleClickOutside(event) {
            const menu = this.$refs.menu; // 参考菜单元素
            const avatar = event.target.closest('.user-info'); // 参考头像元素
            if (menu && !menu.contains(event.target) && !avatar) {
                this.menuVisible = false;
                document.removeEventListener('click', this.handleClickOutside);
            }
        },
        // 生成 ECharts 配置的方法
        generateChartOption(type, data) {
            if (!Array.isArray(data) || data.length === 0) {
                console.error('Invalid data for chart generation.');
                return {};
            }

            const keys = Object.keys(data[0]);
            if (keys.length < 2) {
                console.error('Data does not have enough keys for chart generation.');
                return {};
            }

            const categories = data.map(item => item[keys[0]]);
            const values = data.map(item => item[keys[1]]);
            console.log('Categories:', categories);
            console.log('Values:', values);

            // 定义颜色主题
            const colorPalette = ['#5470C6', '#91CC75', '#EE6666', '#FAC858', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4', '#EA7CCC'];

            let option = {
                color: colorPalette,
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow' // 改为阴影指示器
                    },
                    backgroundColor: 'rgba(50,50,50,0.7)',
                    textStyle: {
                        color: '#fff'
                    }
                },
                legend: {
                    textStyle: {
                        color: '#333'
                    },
                    top: '10%' // 确保图例位于顶部
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%', // 增加底部留白以放置标题
                    containLabel: true
                },
                series: []
            };

            switch (type) {
                case 'bar':
                    option.title = {
                        text: '',
                        left: 'center',
                        bottom: '5%', // 设置标题位于底部
                        textStyle: {
                            color: '#333',
                            fontSize: 18
                        }
                    };
                    option.xAxis = {
                        type: 'category',
                        data: categories,
                        axisLine: {
                            lineStyle: {
                                color: '#999'
                            }
                        },
                        axisLabel: {
                            color: '#666'
                        }
                    };
                    option.yAxis = {
                        type: 'value',
                        axisLine: {
                            lineStyle: {
                                color: '#999'
                            }
                        },
                        axisLabel: {
                            color: '#666'
                        },
                        splitLine: {
                            lineStyle: {
                                type: 'dashed'
                            }
                        }
                    };
                    option.series.push({
                        name: keys[1],
                        type: 'bar',
                        data: values,
                        itemStyle: {
                            barBorderRadius: [5, 5, 0, 0],
                            shadowColor: 'rgba(0,0,0,0.1)',
                            shadowBlur: 10
                        },
                        label: {
                            show: true,
                            position: 'top',
                            color: '#333',
                            fontWeight: 'bold'
                        }
                    });
                    break;
                case 'pie':
                    option.title = {
                        text: '',
                        left: 'center',
                        bottom: '5%', // 设置标题位于底部
                        textStyle: {
                            color: '#333',
                            fontSize: 18
                        }
                    };
                    option.tooltip = {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)',
                        backgroundColor: 'rgba(50,50,50,0.7)',
                        textStyle: {
                            color: '#fff'
                        }
                    };
                    // 饼图不需要x轴和y轴
                    delete option.xAxis;
                    delete option.yAxis;
                    option.series.push({
                        name: keys[1],
                        type: 'pie',
                        radius: '50%',
                        data: data.map(item => ({ name: item[keys[0]], value: item[keys[1]] })),
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },
                        label: {
                            formatter: '{b}: {c} ({d}%)',
                            color: '#333',
                            fontWeight: 'bold'
                        }
                    });
                    break;
                case 'line':
                    option.title = {
                        text: '',
                        left: 'center',
                        bottom: '5%', // 设置标题位于底部
                        textStyle: {
                            color: '#333',
                            fontSize: 18
                        }
                    };
                    option.xAxis = {
                        type: 'category',
                        data: categories,
                        axisLine: {
                            lineStyle: {
                                color: '#999'
                            }
                        },
                        axisLabel: {
                            color: '#666'
                        }
                    };
                    option.yAxis = {
                        type: 'value',
                        axisLine: {
                            lineStyle: {
                                color: '#999'
                            }
                        },
                        axisLabel: {
                            color: '#666'
                        },
                        splitLine: {
                            lineStyle: {
                                type: 'dashed'
                            }
                        }
                    };
                    option.tooltip = {
                        trigger: 'axis',
                        backgroundColor: 'rgba(50,50,50,0.7)',
                        textStyle: {
                            color: '#fff'
                        }
                    };
                    option.series.push({
                        name: keys[1],
                        type: 'line',
                        data: values,
                        smooth: false, // 平滑曲线
                        symbol: 'circle',
                        symbolSize: 8,
                        lineStyle: {
                            width: 3
                        },
                        areaStyle: {
                            color: 'rgba(84, 112, 198, 0.2)'
                        },
                        itemStyle: {
                            color: '#5470C6'
                        },
                        label: {
                            show: true,
                            position: 'top',
                            color: '#333',
                            fontWeight: 'bold'
                        }
                    });
                    break;
                default:
                    console.error('Unsupported chart type:', type);
            }

            console.log('Chart Option:', option);
            return option;
        },
        parseMarkdown(text) {
            if (typeof md !== 'object' || typeof md.render !== 'function') {
                console.error('markdown-it is not loaded correctly.');
                return text; // 返回原始文本以避免进一步错误
            }
            const rawHtml = md.render(text);
            return DOMPurify.sanitize(rawHtml);
        },
        removeFirstLine(content) {
            return content.split('\n').slice(1).join('\n');
        },
    },
    watch: {

    }
});
